package com.zlyx.easy.core.utils;

import java.nio.file.FileSystems;
import java.nio.file.PathMatcher;
import java.nio.file.Paths;
import java.util.Collection;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <p>
 * url配置工具类
 * </p>
 *
 * @author 赵光
 * @since 2019年1月11日
 */
public class UrlUtils {

	private static final Logger logger = LoggerFactory.getLogger(UrlUtils.class);

	public static final String SLASH = "/";

	/**
	 * url匹配
	 *
	 * @param matchUrls matchUrls
	 * @param url       url
	 * @return
	 */
	public static boolean match(Collection<String> matchUrls, String url) {
		if (matchUrls == null || matchUrls.isEmpty()) {
			logger.debug("matchUrls is empty");
			return false;
		}
		if (matchUrls.contains(url)) {
			logger.debug("matchUrls contains url");
			return true;
		}
		for (String matchUrl : matchUrls) {
			if (match(matchUrl, url)) {
				logger.debug("url = {}, matchUrl = {}", url, matchUrl);
				return true;
			}
		}
		return false;
	}

	/**
	 * url匹配
	 *
	 * @param matchUrl matchUrl
	 * @param url      url
	 * @return
	 */
	public static boolean match(String matchUrl, String url) {
		try {
			if (StringUtils.isBlank(matchUrl) || StringUtils.isBlank(url)) {
				logger.debug("url = {}, matchUrl = {}", url, matchUrl);
				return false;
			}
			if (!StringUtils.startsWith(url, SLASH)) {
				url = SLASH + url;
			}
			PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:**" + matchUrl);
			return matcher.matches(Paths.get(url));
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return false;
		}
	}

	public static void main(String[] args) {
		System.out.println(UrlUtils.match("user/*", "user/info")); // true
		System.out.println(UrlUtils.match("user/*", "user/info/1")); // false
		System.out.println(UrlUtils.match("user/**", "user/info")); // true
		System.out.println(UrlUtils.match("user/**", "user/info/1")); // true
		System.out.println(UrlUtils.match("/user/**", "user")); // true
		System.out.println(UrlUtils.match("/user/**", "/user")); // false
		System.out.println(UrlUtils.match("*", "/user/info/1111")); // true
	}
}
